package cn.edu.lingnan.service.impl;

import cn.edu.lingnan.mapper.ClassMapper;
import cn.edu.lingnan.mapper.StudentMapper;
import cn.edu.lingnan.service.ClassService;
import cn.edu.lingnan.user.Statistics.StudentStatsVo;
import cn.edu.lingnan.user.dtos.ClassQueryDTO;
import cn.edu.lingnan.user.dtos.ClassStudentQueryDTO;
import cn.edu.lingnan.user.pojos.Class;
import cn.edu.lingnan.user.pojos.PageBean;
import cn.edu.lingnan.user.vos.ClassVO;
import cn.edu.lingnan.user.vos.UserVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ClassServiceImpl implements ClassService {

    @Autowired
    private ClassMapper classMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageBean getClassList(ClassQueryDTO queryDTO) {
        PageHelper.startPage(queryDTO.getPage(), queryDTO.getSize());
        //条件查询参数去除空格
        if (queryDTO.getClassName()!= null) {
            queryDTO.setClassName(queryDTO.getClassName().trim());
        }
        Page<ClassVO> classes = classMapper.getClassList(queryDTO);
        //统计班级人数
        for (ClassVO classVO : classes) {
            Integer studentCount = classMapper.getStudentCountByClassId(classVO.getId());
            classVO.setStudentCount(studentCount);
        }

        return new  PageBean(classes.getTotal(),classes.getResult());
    }

    @Override
    public Class getClassInfo(Integer id) {
        Class classInfo = classMapper.getClassInfo(id);
        if (classInfo != null){
            classInfo.setStudentCount(classMapper.getStudentCountByClassId(classInfo.getId()));
            return classInfo;
        }

        return  null;
    }

    @Override
    public void addClass(Class classInfo) {
        classMapper.addClass(classInfo);
    }

    @Override
    public void updateClass(Class classInfo) {
        classMapper.updateClass(classInfo);
    }

    @Override
    @Transactional
    public boolean deleteClassById(Integer id) {
        boolean flag = classMapper.deleteClassById(id);
        if (!flag) {
            // 抛出异常，以确保事务回滚
            throw new RuntimeException("删除操作失败");
        }
        return true;
    }

    @Override
    public List<Integer> getStudentIdListByClassId(Integer id) {
        List<Integer> list = classMapper.getStudentIdListByClassId(id);
        return list;
    }

    @Override
    public PageBean getStudentList(ClassStudentQueryDTO queryDTO,Integer id) {
        PageHelper.startPage(queryDTO.getPage(), queryDTO.getSize());
        //条件查询参数去除空格
        if (queryDTO.getStudentName()!= null) {
            queryDTO.setStudentName(queryDTO.getStudentName().trim());
        }
        Page<UserVO> classes = classMapper.getStudentList(queryDTO,id);

        return new  PageBean(classes.getTotal(),classes.getResult());
    }

    @Override
    @Transactional
    public boolean removeStudent(Integer studentId, Integer classId) {
        boolean flag = classMapper.removeStudent(studentId,classId);
        if (!flag) {
            // 抛出异常，以确保事务回滚
            throw new RuntimeException("删除操作失败");
        }
        return true;
    }

    @Override
    public StudentStatsVo getStudentStats(Integer classId) {
        // 1. 根据班级ID查询学生ID列表
        List<Integer> studentIdList = classMapper.getStudentIdListByClassId(classId);
        if (CollectionUtils.isEmpty(studentIdList)) {
            log.warn("班级[{}]没有学生数据", classId);
            return new StudentStatsVo(); // 返回空统计对象
        }

        // 2. 构建统计VO
        StudentStatsVo vo = new StudentStatsVo();

        // 3. 设置基础统计
        vo.setTotal(studentIdList.size());
        vo.setMale(studentMapper.countBySex(studentIdList, 1)); // 男生数
        vo.setFemale(vo.getTotal()- vo.getMale()); // 女生数

        // 使用正确的转换方法：
        vo.setProvinceStats(convertStringKeyResult(
                studentMapper.countByProvince(studentIdList),
                "provinceName"
        ));

        vo.setCityStats(convertStringKeyResult(
                studentMapper.countByCity(studentIdList),
                "cityName"
        ));

        vo.setBirthYearStats(convertIntegerKeyResult(
                studentMapper.countByBirthYear(studentIdList),
                "birthYear"
        ));

        vo.setEthnicityStats(convertStringKeyResult(
                studentMapper.countByEthnicity(studentIdList),
                "ethnicityName"
        ));

        vo.setPoliticalStats(convertPoliticalResult(
                studentMapper.countByPoliticalStatus(studentIdList)
        ));

        return vo;
    }

    // 通用转换方法（处理数值型Key）
    private Map<Integer, Integer> convertIntegerKeyResult(
            List<Map<String, Object>> list,
            String keyName
    ) {
        if (CollectionUtils.isEmpty(list)) {
            return new HashMap<>();
        }
        return list.stream()
                .collect(Collectors.toMap(
                        map -> ((Number) map.get(keyName)).intValue(),
                        map -> ((Number) map.get("count")).intValue()
                ));
    }

    // 处理字符串Key的转换
    private Map<String, Integer> convertStringKeyResult(
            List<Map<String, Object>> list,
            String keyName
    ) {
        if (CollectionUtils.isEmpty(list)) {
            return new HashMap<>();
        }
        return list.stream()
                .collect(Collectors.toMap(
                        map -> map.get(keyName).toString(), // 确保转为String
                        map -> ((Number) map.get("count")).intValue()
                ));
    }

    // 政治面貌转换（返回数值型Key）
    private Map<Integer, Integer> convertPoliticalResult(
            List<Map<String, Object>> list
    ) {
        if (CollectionUtils.isEmpty(list)) {
            return Map.of(0, 0, 1, 0, 2, 0); // 返回数值键的默认值
        }
        return list.stream()
                .collect(Collectors.toMap(
                        map -> ((Number) map.get("politicalStatus")).intValue(),
                        map -> ((Number) map.get("count")).intValue()
                ));
    }

}
